<template>
  <el-dialog
    :class="'el-dialog-theme3'"
    append-to-body
    draggable
    :close-on-click-modal="false"
    v-model="open"
    v-if="open"
    :title="title"
    @close="dialogClose"
    class="dialog1"
    width="1880"
    :fullscreen="true"
  >
    <el-tabs
      v-model="activityName"
      class="demo-tabs"
      @tab-change="tabChange"
      :before-leave="beforeLeave"
    >
      <el-tab-pane
        label="选样质控"
        name="first"
        v-if="userStatus === 0 && userStepId == 0"
      >
        <xzzk
          ref="xzzkRef"
          v-if="activityName == 'first'"
          @lMId="getLMId"
          @setMyIdEmpty="setMyIdEmpty"
          @returnChangeMethod="returnChangeMethod"
        />
      </el-tab-pane>
      <el-tab-pane
        v-for="(item, index) in tabsView1"
        :label="item.tableName"
        :name="item.tFId"
        :key="index"
      >
        <template v-if="item.modelType == 3">
          <zbtb
            ref="zbtbRef"
            v-if="activityName == item.tFId"
            :params="item"
            :projectId="projectId"
            :methodId="methodId"
            :lMId="lMId"
            :pId="pId"
          />
        </template>

        <template v-else-if="item.modelType == 7 || item.isPrimary == 2">
          <labLine
            ref="lineRef"
            v-if="activityName == item.tFId"
            :params="item"
            :methodId="methodId"
            @editBq="editBq"
          />
        </template>

        <template v-else>
          <pxyb
            ref="txybRef"
            v-if="activityName == item.tFId"
            :params="item"
            :myId="myId"
            :methodId="methodId"
          />
        </template>
      </el-tab-pane>
    </el-tabs>
    <el-button
      type="success"
      style="position: absolute; top: 50px; right: 150px"
      @click="selectBq"
      v-if="userStatus == 0 && userStepId == 0"
    >
      选择标准曲线表
    </el-button>
    <el-button
      type="success"
      style="position: absolute; top: 50px; right: 10px"
      @click="addBqb"
      v-if="userStatus == 0 && userStepId == 0"
    >
      新建标准曲线表
    </el-button>
    <el-dialog
      :class="'el-dialog-theme3'"
      append-to-body
      draggable
      :close-on-click-modal="false"
      v-model="selectAddBqOpen"
      title="选择标准曲线表"
    >
      <el-form label-width="90" :model="queryParams" ref="queryRef">
        <el-row>
          <el-col :span="6">
            <el-form-item label="标准曲线表：" prop="lineTitle">
              <el-input
                clearable
                v-model="queryParams.lineTitle"
                @keyup.enter="handleLineList"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="有效时间：">
              <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="检测项目：" prop="sampleName">
              <el-input
                clearable
                v-model="queryParams.sampleName"
                @keyup.enter="handleLineList"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-row justify="end">
              <el-button type="success" @click="handleLineList">搜索</el-button>
              <el-button class="business resetBtn" @click="resetQuery">重置</el-button>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
      <el-table
        :data="lineDataList"
        v-loading="listLoading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="标准曲线表" align="center" prop="lineTitle" />
        <el-table-column
          label="创建人"
          align="center"
          width="120"
          prop="createUserName"
        />
        <el-table-column label="创建时间" align="center" width="130" prop="createDate" />
        <el-table-column label="有效时间" align="center" width="130" prop="yxDate" />
        <el-table-column label="标样" align="center" width="80" prop="jclb" />
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleLineList"
      />

      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="handleAddSelectLines">选择</el-button>
          <el-button type="danger" @click="selectAddBqOpen = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      :class="'el-dialog-theme3'"
      append-to-body
      draggable
      :close-on-click-modal="false"
      v-model="addBqOpen"
      :title="aoreTitle"
      @close="addBqClose"
    >
      <el-form :model="addBqForm" label-width="100" :rules="addBqRules" ref="formRef">
        <el-form-item label="标曲表名称：" prop="lineTitle">
          <el-input v-model="addBqForm.lineTitle" clearable />
        </el-form-item>
        <el-form-item label="模板：" prop="tableId">
          <el-select
            v-model="addBqForm.tableId"
            clearable
            filterable
            remote
            reserve-keyword
            remote-show-suffix
            :loading="loading"
            style="width: 100%"
          >
            <el-option
              v-for="item in addBqTemList"
              :label="item.tableName"
              :value="item.tableId"
              :key="item.tableId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间：" prop="createDate">
          <el-date-picker
            v-model="addBqForm.createDate"
            placeholder="请选择创建时间"
            type="date"
            value-format="YYYY-MM-DD"
            @change="setYxDate"
          />
        </el-form-item>
        <el-form-item label="有效时间：" prop="yxDate">
          <el-date-picker
            v-model="addBqForm.yxDate"
            placeholder="请选择有效时间"
            type="date"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="样品类型：" prop="sampleType">
          <el-radio-group
            v-model="addBqForm.sampleType"
            :disabled="addBqForm.sampleList && addBqForm.sampleList.length > 0"
          >
            <el-radio :label="0">标准物质</el-radio>
            <el-radio :label="1">自制溶液</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="选择样品：" prop="id">
          <el-select
            v-model="addBqForm.sampleList"
            placeholder="请选择"
            filterable
            multiple
            remote
            reserve-keyword
            remote-show-suffix
            :remote-method="remoteMethod2"
            :loading="loading6"
            class="custom-select1"
            style="width: 100%"
            @change="idChange"
          >
            <el-option
              v-for="item in byList"
              :label="item.code + '　' + item.jcxmName"
              :value="item.id"
              :key="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="样品数量：" prop="sampleCount">
          <el-input-number v-model="addBqForm.sampleCount" :min="1" :max="20" />
        </el-form-item>
        <el-form-item label="选择谱图：">
          <fileUpload
            v-model="addBqForm.fileList"
            :limit="10000"
            :fileType="[
              'png',
              'jpg',
              'bmp',
              'gif',
              'tif',
              'doc',
              'docx',
              'xls',
              'xlsx',
              'txt',
              'pdf',
            ]"
          >
          </fileUpload>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="handleSc">生成标准曲线表</el-button>
          <el-button type="danger" @click="addBqOpen = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <template #footer>
      <div class="dialog-footer">
        <el-row style="justify-content: end" class="editFormItem">
          <template v-if="userStatus == 0">
            <el-form-item
              label="加标回收表："
              prop="formula"
              label-width="100"
              v-if="selectedModelType == 5"
              style="margin-right: 10px"
            >
              <el-select v-model="jbTableId" style="width: 270px" filterable>
                <el-option
                  v-for="item in jbTableList"
                  :label="item.tableName"
                  :value="item.tableId"
                  :key="item.tableId"
                />
              </el-select>
            </el-form-item>
            <el-button
              type="success"
              @click="handleSwitchJbTable"
              v-if="selectedModelType == 5"
              >确 定</el-button
            >
            <el-form-item
              label="引用控件："
              label-width="100"
              v-if="selectedModelType == 6 || selectedModelType == 23"
              style="margin-right: 10px"
            >
              <el-select v-model="jzComponentId" style="width: 240px" filterable>
                <el-option
                  v-for="item in jzComponentList"
                  :label="item.componentName"
                  :value="item.componentId"
                  :key="item.componentId"
                />
              </el-select>
            </el-form-item>
            <el-button
              type="success"
              @click="handleSaveJzComponent"
              v-if="selectedModelType == 6 || selectedModelType == 23"
              >确 定</el-button
            >
            <el-form-item
              label="公式选择："
              prop="formula"
              label-width="80"
              v-if="formulaList.length"
            >
              <el-select
                v-model="formula"
                style="width: 500px"
                @change="handleFormula"
                clearable
                filterable
              >
                <el-option
                  v-for="item in formulaList"
                  :key="item.formulaId"
                  :value="item.formulaId"
                  :label="item.formulaExpressDisplay"
                >
                  <el-tooltip
                    class="box-item"
                    effect="customized"
                    placement="top"
                    :content="item.formulaExpressDisplay"
                  >
                    <div
                      style="
                        white-space: nowrap;
                        overflow: hidden;
                        text-overflow: ellipsis;
                      "
                    >
                      {{ item.formulaExpressDisplay }}
                    </div>
                  </el-tooltip>
                </el-option>
              </el-select>
            </el-form-item>
            <el-button
              style="background-color: #0066ff; color: #fff; margin-left: 15px"
              @click="eventResult"
              v-if="showFormulaBtn && activityName != 'first'"
              >计算结果</el-button
            >
            <el-button type="success" @click="submitFileForm">保 存</el-button>
            <el-dropdown
              split-button
              type="success"
              @click="handleSubmitReview(1)"
              style="margin-left: 10px"
              v-if="activityName !== 'first'"
            >
              提交
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleSubmitReview(1)">
                    <el-button type="success" link>随机审核</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item @click="handleSubmitReview(2)">
                    <el-button type="success" link>手动审核</el-button>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-dropdown
              split-button
              type="success"
              style="margin: 0 10px"
              v-if="activityName != 'first'"
            >
              操作

              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleReloadTable">
                    <el-button type="success" link>重载数据</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item @click="showRecord">
                    <el-button type="success" link>流程记录</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item @click="printDateForm">
                    <el-button type="success" link>打印</el-button>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-button type="danger" @click="handleClear" v-if="userStatus == 0"
              >取 消</el-button
            >
          </template>

          <template v-else>
            <el-button type="success" @click="showRecord">流程记录</el-button>
            <el-button type="success" @click="printDateForm">打印</el-button>
            <el-button type="success" @click="exportDateFormPdf" v-show="lMId && myId">导出pdf</el-button>
            <el-button type="danger" @click="handleClear">关 闭</el-button>
          </template>
        </el-row>
      </div>
    </template>
    <!-- 流程记录 -->
    <el-dialog
      :class="'el-dialog-theme3'"
      append-to-body
      draggable
      v-model="recordOpen"
      :title="recordTitle"
      width="950"
    >
      <el-table :data="recordList" v-loading="loadingRecord" max-height="60vh">
        <el-table-column label="步骤" align="center">
          <template #default="scope">
            <span v-if="scope.row.userStepId == 0">化验员填报</span>
            <span v-if="scope.row.userStepId == 1">实验室复核</span>
            <span v-if="scope.row.userStepId == 2">实验室审核</span>
          </template>
        </el-table-column>
        <el-table-column label="姓名" prop="nickName" align="center" />
        <el-table-column label="开始时间" prop="createTime" align="center" />
        <el-table-column label="结束时间" prop="finishTime" />
        <el-table-column label="状态">
          <template #default="scope">
            <span v-if="scope.row.userStatus == 0">未完成</span>
            <span v-if="scope.row.userStatus == 1">已完成</span>
            <span v-if="scope.row.userStatus == 2">退回</span>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="danger" @click="recordOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      :class="'el-dialog-theme3'"
      append-to-body
      draggable
      :close-on-click-modal="false"
      v-model="submitOpen"
      :title="submitTitle"
      width="700px"
      @close="submitClose"
    >
      <el-row justify="center">
        <el-col :span="4" style="padding-left: 10px; padding-top: 10px">
          <el-steps direction="vertical" :active="userStepId + 1">
            <el-step title="填报" />
            <el-step title="复核" />
            <el-step title="审核" />
          </el-steps>
        </el-col>
        <el-col :span="20" class="dialogUser">
          <el-input
            style="margin-bottom: 10px"
            v-model="filterText"
            clearable
            placeholder="请输入人员名称"
            prefix-icon="UserFilled"
          >
          </el-input>
          <el-scrollbar height="50vh" ref="scrollbarRef">
            <el-tree
              :data="treeData"
              :props="defaultProps"
              :default-expand-all="true"
              @node-click="nodeClick"
              node-key="userId"
              :highlight-current="true"
              ref="treeRef"
              v-loading="treeLoading"
              :filter-node-method="filterNode"
            />
          </el-scrollbar>
        </el-col>
      </el-row>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="submitConfirm">确认</el-button>
          <el-button type="danger" @click="submitOpen = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup>
import xzzk from "./components/xzzk.vue";
import zbtb from "./components/zbtb.vue";
import pxyb from "./components/pxyb.vue";
import labLine from "./components/line.vue";
import { getCurrentTime, getThreeDate } from "@/api/common";
import {
  myTaskFormList,
  saveXzzk,
  submitReview,
  getBzwzList,
  lineList,
  addSelectLines,
  saveSc,
  editStandard,
  getSelectView,
  queryJzComponentList,
  saveJzComponent,
} from "@/api/lab/labMethod";
import { listTemplate } from "@/api/templateEditor/table";
import { getTreeList } from "@/api/system/newUser";
import { userRecordList, updateTaskForm } from "@/api/myTask/myTask";
import { nextTick, watch } from "vue";
import bus from "@/utils/eventBus";
const { proxy } = getCurrentInstance();
const activityName = ref("first");
const total = ref(0);
const xzzkRef = ref(null);
const lineRef = ref(null);
const zbtbRef = ref(null);
const txybRef = ref(null);
const open = ref(false);
const title = ref("");
const parentId = ref("");
const lMId = ref("");
const myId = ref("");
const projectId = ref("");
const methodId = ref("");
const formula = ref("");
const showFormulaBtn = ref(false);
const recordOpen = ref(false);
const recordTitle = ref("流程记录");
const recordList = ref([]);
const loadingRecord = ref(false);
const emit = defineEmits(["close"]);
const jbTableId = ref();
const jbTableList = ref([]);
const selectedModelType = ref();
const jzComponentList = ref([]);
const jzComponentId = ref();
const nextUser = ref({});
watch(
  () => open.value,
  (val) => {
    if (!val) {
      activityName.value = "first";
    }
  }
);

function dialogClose() {
  parentId.value = "";
  lMId.value = "";
  myId.value = "";
  projectId.value = "";
  tabsView1.value = [];
  formulaList.value = [];
  methodId.value = "";
  bus.off("deleteTabView");
  bus.off("getFormulaList");
  bus.off("handleReloadTable" + activityName.value);
  emit("close");
}

function handleClear() {
  parentId.value = "";
  lMId.value = "";
  myId.value = "";
  projectId.value = "";
  tabsView1.value = [];
  formulaList.value = [];
  methodId.value = "";
  open.value = false;
  bus.off("getFormulaList");
  bus.off("handleReloadTable" + activityName.value);
  emit("close");
}

function getLMId(val) {
  lMId.value = val;
}

function setMyIdEmpty() {
  myId.value = "";
}

function beforeLeave(newVal, oldVal) {
  if (oldVal !== "first" && userStatus.value == 0) {
    bus.emit("submit" + oldVal, { isAutoSave: true, isShowTable: false });
  }
}

function tabChange(name) {
  nextTick(() => {
    formula.value = "";
    formulaList.value = [];
    if (name == "first") {
      if (!parentId.value) return;
      xzzkRef.value.parentId = parentId.value;
      xzzkRef.value.lMId = lMId.value;
      xzzkRef.value.projectId = projectId.value;
      xzzkRef.value.getList();
      xzzkRef.value.getNumber();
      xzzkRef.value.getSelectedListView();
      xzzkRef.value.getSelectForm();
      xzzkRef.value.handleSampleListCount();
      selectedModelType.value = null;
    } else {
      const selectedTab = tabsView1.value.filter((view) => {
        return view.tFId == name;
      });
      if (!selectedTab || selectedTab.length == 0) {
        selectedModelType.value = null;
        return;
      }
      selectedModelType.value = selectedTab[0].modelType;
      //查询加标回收表
      if (selectedModelType.value == 5) {
        listTemplate({ modelType: selectedModelType.value }).then((res) => {
          jbTableList.value = res.data;
          if (jbTableList.value && jbTableList.value.length > 0) {
            jbTableId.value = selectedTab[0].tableId;
          }
        });
      } else if (selectedModelType.value == 6 || selectedModelType.value == 23) {
        queryJzComponentList(lMId.value).then((res) => {
          if (res.data.componentList.length > 0) {
            jzComponentList.value = res.data.componentList;
          }
          if (res.data.relComponentId || res.data.columnl2) {
            nextTick(() => {
              jzComponentId.value =
                selectedModelType.value == 6
                  ? res.data.relComponentId
                  : res.data.columnl2;
            });
          }
        });
      }
    }
  });
}

function handleSaveJzComponent() {
  if (!jzComponentId.value) {
    proxy.$modal.msgError("请选择要引用的控件！");
    return;
  }
  const selectedJzComponentList = jzComponentList.value.filter((item) => {
    return item.componentId == jzComponentId.value;
  });
  if (selectedJzComponentList.length < 1) return;
  const data = { lMId: lMId.value };
  if (selectedModelType.value == 6) {
    //校准表
    data.relTableId = selectedJzComponentList[0].tableId;
    data.relComponentId = selectedJzComponentList[0].componentId;
  } else if (selectedModelType.value == 23) {
    data.columnl1 = selectedJzComponentList[0].tableId;
    data.columnl2 = selectedJzComponentList[0].componentId;
  }
  saveJzComponent(data).then((res) => {
    const relDataList = res.data;
    const data = { modelType: selectedModelType.value, relDataList: relDataList };
    bus.emit("relJzDataList", data);
  });
}
//切换加标回收表
function handleSwitchJbTable() {
  if (!activityName.value || !jbTableId.value) {
    proxy.$modal.msgError("系统错误，缺少参数！");
    return;
  }
  proxy.$modal
    .confirm("切换加标回收表会导致当前表的数据丢失，确定要继续吗？")
    .then(() => {
      const dataParams = {
        tFId: activityName.value,
        tableId: jbTableId.value,
        formId: -1,
      };
      proxy.$modal.loading("正在切换加标回收表，请稍候...");
      updateTaskForm(dataParams)
        .then((res) => {
          if (res.code == 200) {
            proxy.$modal.closeLoading();
            proxy.$modal.msgSuccess("切换成功！");
            tabsView1.value = [];
            nextTick(() => {
              tabsView(activityName.value);
            });
          }
        })
        .catch(() => {
          proxy.$modal.closeLoading();
        });
    });
}

const tabsView1 = ref([]);
const userStatus = ref(0);
const userStepId = ref(0);
const pId = ref("");

function tabsView(selectedTab) {
  if (!methodId.value) {
    getSelectView(lMId.value).then((res) => {
      open.value = true;
      title.value = "数据填报";
      parentId.value = res.data.parentId;
      methodId.value = res.data.methodId;
      if (res.data.projectId) {
        projectId.value = res.data.projectId;
      }
      myTaskFormList(myId.value).then((res) => {
        if (
          !res.data ||
          res.data.myTaskFormList.length === 0 ||
          !res.data.myTaskFormList
        ) {
          getView();
          return;
        }
        tabsView1.value = res.data.myTaskFormList;
        userStatus.value = res.data.userStatus;
        userStepId.value = res.data.userStepId;
        if (res.data.nextUserId) {
          nextUser.value.nextUserId = res.data.nextUserId;
          nextUser.value.nextUserName = res.data.nextNickName;
        }
        nextTick(() => {
          activityName.value = res.data.myTaskFormList[0].tFId;
        });
      });
    });
  } else {
    myTaskFormList(myId.value).then((res) => {
      if (!res.data || res.data.myTaskFormList.length === 0 || !res.data.myTaskFormList) {
        getView();
        return;
      }
      tabsView1.value = res.data.myTaskFormList;
      userStatus.value = res.data.userStatus;
      userStepId.value = res.data.userStepId;
      if (res.data.nextUserId) {
        nextUser.value.nextUserId = res.data.nextUserId;
        nextUser.value.nextUserName = res.data.nextNickName;
      }
      nextTick(() => {
        activityName.value = selectedTab ? selectedTab : res.data.myTaskFormList[0].tFId;
      });
    });
  }
}

function getView() {
  xzzkRef.value.parentId = parentId.value;
  xzzkRef.value.lMId = lMId.value;
  xzzkRef.value.getList();
  xzzkRef.value.getNumber();
  xzzkRef.value.getSelectedListView();
  xzzkRef.value.getSelectForm();
}

function submitFileForm() {
  if (activityName.value == "first") {
    if (xzzkRef.value.selectedTotal === 0) {
      proxy.$modal.msgError("已选样品列表中至少存在一条数据");
      return;
    }
    proxy.$modal.loading("正在生成原始记录表，请稍候...");
    saveXzzk(myId.value || lMId.value)
      .then((res) => {
        myId.value = res.data;
        proxy.$modal.closeLoading();
        proxy.$modal.msgSuccess("保存成功");
        tabsView();
      })
      .catch(() => {
        proxy.$modal.closeLoading();
      });
  } else {
    bus.emit("submit" + activityName.value, { isAutoSave: false, isShowTable: false });
  }
}
function handleReloadTable() {
  bus.emit("handleReloadTable" + activityName.value);
}

// -------------------------------------------手动审核------------------------------------------
const submitOpen = ref(false);
const submitTitle = ref("选择提交人");
const treeData = ref([]);
const defaultProps = ref({ label: "nickName", children: "children" });
const treeLoading = ref(false);
const userId = ref("");
const filterText = ref("");

function submitClose() {
  filterText.value = "";
  userId.value = "";
  treeData.value = [];
}

function handleSubmitReview(bs) {
  let data = {
    method: handleSubmit,
    bs: bs,
  };
  bus.emit("submitCallback", data);
}

function handleSubmit(bs) {
  if (bs == 1) {
    proxy.$modal.loading("正在提交,请稍后");
    submitReview({ myId: myId.value })
      .then((res) => {
        proxy.$modal.msgSuccess("提交成功");
        bus.emit("dbSave");
        handleClear();
        proxy.$modal.closeLoading();
      })
      .catch(() => {
        proxy.$modal.closeLoading();
      });
  } else {
    submitOpen.value = true;
    treeLoading.value = true;
    getTreeList().then((res) => {
      treeData.value = proxy.handleTree(res.data, "userId");
      treeLoading.value = false;
      if (nextUser.value.nextUserId) {
        nextTick(() => {
          filterText.value = nextUser.value.nextUserName;
        });
      }
    });
  }
}

function nodeClick(val) {
  userId.value = "";
  if (val.userType == 1) {
    userId.value = val.userId;
  }
}

function submitConfirm() {
  if (!userId.value) {
    proxy.$modal.msgError("未选择人员");
    return;
  }
  proxy.$modal.confirm("确认要提交吗？").then(function () {
    proxy.$modal.loading("正在提交,请稍后");
    submitReview({ myId: myId.value, userId: userId.value })
      .then((res) => {
        proxy.$modal.msgSuccess("提交成功");
        filterText.value = "";
        userId.value = "";
        treeData.value = [];
        submitOpen.value = false;
        bus.emit("dbSave");
        handleClear();
        proxy.$modal.closeLoading();
      })
      .catch(() => {
        proxy.$modal.closeLoading();
      });
  });
}

function filterNode(value, data) {
  if (!value) {
    return true; // 如果搜索框为空，则显示所有节点
  }
  return data.nickName.includes(value); // 根据节点的 groupName 属性进行名称过滤
}

watch(
  () => filterText.value,
  (val) => {
    proxy.$refs["treeRef"].filter(val);
  }
);

// --------------------------------------------------------------------------------

function handleFormula(formulaId) {
  bus.emit(
    "setResultFormula",
    formulaList.value.filter((item) => formulaId == item.formulaId)
  );
}
function showRecord() {
  recordOpen.value = true;
  loadingRecord.value = true;
  userRecordList(myId.value).then((res) => {
    recordList.value = res.data;
    loadingRecord.value = false;
  });
}

function printDateForm() {
  bus.emit("printDateForm");
}

const formulaList = ref([]);

watch(
  () => open.value,
  () => {
    if (open.value) {
      bus.off("getFormulaList");
      bus.on("getFormulaList", (data) => {
        if (!data) return;
        showFormulaBtn.value = true;
        formulaList.value = data;
        if (formulaList.value && formulaList.value.length > 0) {
          formula.value = formulaList.value[0].formulaId;
          bus.emit("setResultFormula", formulaList.value);
        }
      });

      bus.off("deleteTabView");
      bus.on("deleteTabView", (tFId) => {
        // tabsView1.value = tabsView1.value.filter((item) => {
        //   return item.tFId != tFId;
        // });
        // nextTick(() => {
        //   activityName.value = tabsView1.value[tabsView1.value.length - 1].tFId;
        // });
        tabsView();
      });
    }
  }
);

// 新建标准曲线表
const addBqOpen = ref(false);
const addBqForm = ref({ sampleType: 0, sampleCount: 8 });
const addBqList = ref([]);
const addBqTemList = ref([]);
const addBqRules = ref({
  lineTitle: [{ required: true, message: "标曲表名称不能为空", trigger: "blur" }],
  createDate: [{ required: true, message: "创建时间不能为空", trigger: "blur" }],
  yxDate: [{ required: true, message: "有效日期不能为空", trigger: "blur" }],
  sampleCount: [{ required: true, message: "样品数量不能为空", trigger: "blur" }],
  sampleList: [{ required: true, message: "选择标样不能为空", trigger: "blur" }],
});
function addBqClose() {
  addBqForm.value.sampleType = 0;
  addBqForm.value.lineTitle = "";
  addBqForm.value.fileList = [];
  addBqForm.value.tableId = "";
  addBqForm.value.id = [];
  addBqForm.value.id = [];
  addBqForm.value.sampleList = [];
  jcxmName.value = "";
}

function eventResult() {
  bus.emit("eventResult");
}

function setYxDate(createDate) {
  if (!createDate) {
    delete addBqForm.value.yxDate;
    return;
  }
  getThreeDate({ date: createDate }).then((res1) => {
    addBqForm.value.yxDate = res1.data;
  });
}

function addBqb() {
  ispush.value = true;
  addBqOpen.value = true;
  aoreTitle.value = "新建标准曲线表";
  listTemplate({ modelType: 7 }).then((res) => {
    loading.value = false;
    addBqTemList.value = res.data;
  });
  getCurrentTime().then((res) => {
    addBqForm.value.createDate = res.data;
    getThreeDate({ date: res.data }).then((res1) => {
      addBqForm.value.yxDate = res1.data;
    });
  });
  nextTick(() => {
    if (proxy.$refs["formRef"]) {
      proxy.$refs["formRef"].clearValidate();
    }
  });
}

function editBq(val) {
  listTemplate({ modelType: 7 }).then((res) => {
    addBqTemList.value = res.data;
  });
  editStandard(val).then((res) => {
    addBqForm.value = res.data;
    if (addBqForm.value.labLineSampleList) {
      byList.value = addBqForm.value.labLineSampleList;
      addBqForm.value.sampleList = res.data.labLineSampleList.map((item) => {
        return item.id;
      });
    }
    addBqOpen.value = true;
    ispush.value = false;
    aoreTitle.value = "调整标准曲线表";
  });
}

const loading = ref(false);
const loading6 = ref(false);

const byList = ref([]);
const jcxmName = ref();
function idChange(val) {
  if (val.length > 0) {
    byList.value.forEach((item) => {
      if (item.id == val[0]) {
        jcxmName.value = item.jcxmName;
      }
    });
  } else {
    jcxmName.value = "";
  }
}
function remoteMethod2(val) {
  if (val) {
    if (!addBqForm.value.sampleType === 0 || !addBqForm.value.sampleType === 1) {
      proxy.$modal.msgError("请先选择样品类型");
      byList.value = [];
      return;
    }
    loading6.value = true;
    var temp = {
      sampleType: addBqForm.value.sampleType,
      searchContent: val,
      jcxmName: jcxmName.value,
    };
    setTimeout(() => {
      getBzwzList(temp).then((res) => {
        loading6.value = false;
        byList.value = res.data;
      });
    }, 200);
  } else {
    byList.value = [];
  }
}

const ispush = ref(false);

function handleSc() {
  debugger;
  if (
    !addBqForm.value.tableId &&
    (!addBqForm.value.fileList || addBqForm.value.fileList?.length === 0)
  ) {
    proxy.$modal.msgError("至少有一个模板或谱图");
    return;
  }
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      addBqForm.value.myId = myId.value;
      if (addBqForm.value.fileList?.length > 0) {
        addBqForm.value.fileIdList = addBqForm.value.fileList.map((item) => item.fileId);
      }
      delete addBqForm.value.fileList;
      saveSc(addBqForm.value).then((res) => {
        addBqOpen.value = false;
        if (ispush.value) {
          tabsView1.value.push(res.data); // 追加一个标曲表标签页
          activityName.value = res.data.tFId; //跳转到新增的标曲表
        } else {
          lineRef.value[0].getInfo();
          lineRef.value[0].getTable();
        }
      });
    }
  });
}

const dateRange = ref([]);
const lineDataList = ref([]);
const selectAddBqOpen = ref(false);
const listLoading = ref(false);
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
});
const lineIds = ref();
function selectBq() {
  selectAddBqOpen.value = true;
  handleLineList();
}

function handleLineList() {
  listLoading.value = true;
  lineList(queryParams.value).then((res) => {
    listLoading.value = false;
    lineDataList.value = res.rows;
  });
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleLineList();
}

function handleAddSelectLines() {
  if (!lMId.value || !lineIds.value) {
    proxy.$modal.msgError("请选择标准曲线表！");
    return false;
  }
  addSelectLines(myId.value || lMId.value, lineIds.value).then((res) => {
    tabsView1.value = tabsView1.value.concat(res.data); // 追加一个标曲表标签页
    activityName.value = res.data[0].tFId; //跳转到新增的标曲表
    selectAddBqOpen.value = false;
  });
}

const aoreTitle = ref("");

/** 选择条数  */
function handleSelectionChange(selection) {
  lineIds.value = selection.map((item) => item.lineId);
}

function returnChangeMethod(val) {
  if (val.close) {
    handleClear();
    return;
  }
  lMId.value = val.lMId;
  parentId.value = val.parentId;
  methodId.value = val.methodId;
  tabsView1.value = [];
  // myId.value = "";
  getView();
}

function exportDateFormPdf() {
  proxy.download(
    "/lims/tablePdf/pcViewPdf/" + lMId.value + "/" + myId.value,
    {},
    `原始记录表.pdf`
  );
}
defineExpose({
  open,
  title,
  parentId,
  lMId,
  myId,
  methodId,
  projectId,
  pId,
  getView,
  tabsView,
});
</script>

<style lang="scss" scoped>
.editFormItem :deep(.el-form-item) {
  margin-bottom: 0px !important;
}

/** 解决手动选择人员框时 el-scrollbar遮挡footer中的按钮导致无法点击*/
.dialogUser .el-scrollbar {
  height: 90%;
}
</style>
